package com.turing.post.report.impl;

import java.math.BigInteger;
import java.util.Date;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.report.util.IssueCardStockDaySettlement;
import com.turing.post.report.util.IssueCardStockDaySettlementDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "report.impl.IssueCardStockDaySettlementDaoImpl")
@Remote
@Local
public class IssueCardStockDaySettlementDaoImpl implements
		IssueCardStockDaySettlementDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	public IssueCardStockDaySettlement getIssueCardStockDaySettlementByKey(
			IssueCardStockDaySettlement icsds) {
		return _em.find(IssueCardStockDaySettlement.class, icsds);
	}

	public Date getMaxTranDate(String issueBranchNo, Date tranDate,
			BigInteger cardFaceId) {
		Query query = _em
				.createNativeQuery("select Max(t.tranDate) from IssueCardStockDaySettlement t "
						+ "where t.issueBranchNo = ?1 and t.tranDate < ?2 and t.cardFaceId = ?3");
		query.setParameter(1, issueBranchNo);
		query.setParameter(2, tranDate);
		query.setParameter(3, cardFaceId);
		return (Date) query.getSingleResult();
	}

	public void insert(IssueCardStockDaySettlement icsds)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, icsds);
	}

	@TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
	public void removeAllIssueCardStockDaySettlementByTranDate(
			String issueCompanyNo, Date tranDate) {
		Query query = _em
				.createNativeQuery("delete from IssueCardStockDaySettlement t "
						+ "where t.issueBranchNo like ?1 and t.tranDate = ?2");
		query.setParameter(1, issueCompanyNo + "%");
		query.setParameter(2, tranDate);
		query.executeUpdate();
	}
}